package com.dragon.aipictures.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.api.aliyunai.model.AliYunAiApi;
import com.dragon.aipictures.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.dragon.aipictures.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.dragon.aipictures.config.RedissonConfig;
import com.dragon.aipictures.domain.Enum.PictureReviewStatusEnum;
import com.dragon.aipictures.domain.Enum.UserRoleEnum;
import com.dragon.aipictures.domain.dto.UploadPictureResult;
import com.dragon.aipictures.domain.dto.request.*;
import com.dragon.aipictures.domain.entity.Picture;
import com.dragon.aipictures.domain.entity.Space;
import com.dragon.aipictures.domain.entity.User;
import com.dragon.aipictures.domain.vo.picture.PictureVO;
import com.dragon.aipictures.domain.vo.user.UserVO;
import com.dragon.aipictures.manager.CosManager;
import com.dragon.aipictures.manager.upload.FilePictureUpload;
import com.dragon.aipictures.manager.upload.PictureUploadTemplate;
import com.dragon.aipictures.manager.upload.UrlPictureUpload;
import com.dragon.aipictures.mapper.pictureMapper;
import com.dragon.aipictures.service.pictureService;
import com.dragon.aipictures.service.spaceService;
import com.dragon.aipictures.service.userService;
import com.dragon.aipictures.util.ColorSimilarUtils;
import com.dragon.aipictures.util.ThrowUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 20390
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-01-21 10:06:58
 */
@Slf4j
@Service
public class pictureServiceImpl extends ServiceImpl<pictureMapper, Picture>
        implements pictureService {


    @Resource
    private CosManager cosManager;
    @Resource
    private userService userService;
    @Resource
    private spaceService spaceService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
    RedissonClient redissonClient = RedissonConfig.createRedissonClient();
    private final String LOCK_REBUILD_CACHE = "LOCK_REBUILD_CACHE";
    private final String LOCK_CACHE_DOUBLE_WRITE = "LOCK_REBUILD_CACHE";
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();
//    @Resource
//    private ThreadPoolExecutor customExecutor;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
//        ThrowUtil.throwIf(loginUser == null, StateCode.NO_AUTH_ERROR);
        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        Long spaceId = pictureUploadRequest.getSpaceId();
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR, "图片不存在");
            //仅本人或管理员可以更新该图片
            if (!ObjectUtil.equals(loginUser.getId(), oldPicture.getUserId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(StateCode.NO_AUTH_ERROR, "无更新权限");
            }
            //如果传了spaceid，只能更新自己的空间，不能更新别人的
            //如果没有传空间id，就只能从数据库中查自己的空间id，然后复用
            if (spaceId == null) {
                spaceId = oldPicture.getSpaceId();
            } else {
                //如果传了空间id，就必须和数据库的保持一致，因为一个用户只能创建一个空间
                if (!ObjectUtil.equals(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(StateCode.PARAMS_ERROR, "空间id不一致");
                }
            }
        }
        // 上传图片，得到信息
        // 按照用户 id 和空间id划分目录
        String uploadPathPrefix = String.format("public/%s", loginUser.getId());
        //非公共图库
        if (spaceId != 0) {
            //如果空间不存在，那么报错
            Space spaceById = spaceService.getById(spaceId);
            if (spaceById == null) {
                throw new BusinessException(StateCode.NOT_FOUND_ERROR, "空间不存在");
            }
            //如果不是空间成员或者管理员，就没有上传权限
            if (!(ObjectUtil.equals(loginUser.getId(), spaceById.getUserId())) && !UserRoleEnum.ADMIN.getValue().equals(loginUser.getUserRole())) {
                throw new BusinessException(StateCode.NO_AUTH_ERROR, "没有上传权限");
            }
            // 校验额度
            if (spaceById.getTotalCount() >= spaceById.getMaxCount()) {
                throw new BusinessException(StateCode.OPERATION_ERROR, "空间条数不足");
            }
            if (spaceById.getTotalSize() >= spaceById.getMaxSize()) {
                throw new BusinessException(StateCode.OPERATION_ERROR, "空间大小不足");
            }

            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicColor(uploadPictureResult.getPicColor());
        picture.setUserId(loginUser.getId());
        picture.setSpaceId(spaceId);
        if (pictureUploadRequest != null && pictureUploadRequest.getPicName() != null) {
            picture.setName(pictureUploadRequest.getPicName());
        }
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 如果 spaceId 是 null 那么设置默认值为 0，如果要分库分表一定要补全 spaceId
        picture.setSpaceId(Objects.isNull(picture.getSpaceId()) ? 0 : picture.getSpaceId());
        //填充审核参数
        fillReviewParams(picture, loginUser);

        // 开启事务,保存图片数据
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != 0) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtil.throwIf(!update, StateCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });

        return PictureVO.objToVo(picture);
    }

    private boolean isValidImageUrl(String fileUrl, List<String> allowedContentTypes) {
        // 提取文件扩展名
        String extension = FileUtil.getSuffix(fileUrl).toLowerCase();

        // 如果 URL 中没有明确的扩展名，则尝试从 MIME 类型推断
        if (StrUtil.isBlank(extension)) {
            for (String contentType : allowedContentTypes) {
                if (contentType.startsWith("image/") && fileUrl.contains(contentType)) {
                    return true;
                }
            }
            return false;
        }

        // 检查扩展名是否在允许的列表中
        return allowedContentTypes.contains(extension);
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();

        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtil.throwIf(count > 300, StateCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(StateCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(StateCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
//            // 检查文件后缀是否符合要求
//            if (!isValidImageUrl(fileUrl, ALLOW_CONTENT_TYPES)) {
//                log.info("图片 URL 不符合允许的内容类型，已跳过: {}", fileUrl);
//                continue;
//            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
            try {
                if (namePrefix == null) {
                    namePrefix = searchText;
                }
                pictureUploadRequest.setPicName(namePrefix + uploadCount);
                pictureUploadRequest.setSpaceId(pictureUploadByBatchRequest.getSpaceId());
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtil.throwIf(spaceId == null || StrUtil.isBlank(picColor), StateCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser == null, StateCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtil.throwIf(space == null, StateCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(StateCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    //图片审核功能
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //校验是否登陆
        //校验参数是否为空f
        Long pictureId = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (pictureId == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "审核参数错误");
        }

        Picture oldPicture = this.getById(pictureId);
        ThrowUtil.throwIf(ObjectUtil.isEmpty(oldPicture), StateCode.NOT_FOUND_ERROR, "图片不存在");
        Integer oldReviewStatus = oldPicture.getReviewStatus();
        if (ObjectUtil.equals(oldReviewStatus, reviewStatus)) {
            throw new BusinessException(StateCode.OPERATION_ERROR, "请勿重复设置");
        }
        //否则就设置更新态
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, picture);
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        boolean save = this.updateById(picture);
        ThrowUtil.throwIf(!save, StateCode.SYSTEM_ERROR, "图片审核失败");
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long spaceId = pictureQueryRequest.getSpaceId();
//        Boolean nullSpaceId = pictureQueryRequest.getNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
//        queryWrapper.isNull(nullSpaceId, "spaceId");

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> listPictureVOByPageWithCache(PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtil.throwIf(size > 20, StateCode.PARAMS_ERROR);
        // 普通用户默认只能查看已过审的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        //这里是将查询条件作为key，这实际上是有问题的，为了节省内存，我还是仅使用图片部分长度作为key，
        //一条记录的部分字段作为value
        // 构建缓存 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "yupicture:listPictureVOByPage:" + hashKey;

        //从缓存中读数据，
        Page<PictureVO> pageByCache = getPageByCache(cacheKey);
        if (pageByCache != null) {
            return pageByCache;
        }

        //如果caffeine和redis都没有命中，那么从数据库中查，进行缓存重建，只需要一个线程进行缓存重建就可以了
        //那么这里肯定需要加一把分布式锁，防止数据库被冲烂
        RLock lock = redissonClient.getLock(LOCK_REBUILD_CACHE);
        try{
            lock.lock();
            pageByCache = getPageByCache(cacheKey);
            if (pageByCache != null) {
                return pageByCache;
            }
            // 查询数据库
            Page<Picture> picturePage = page(new Page<>(current, size),
                    getQueryWrapper(pictureQueryRequest));
            Page<PictureVO> pictureVOPage = getPictureVOPage(picturePage, request);
            putPageByCache(pictureVOPage,cacheKey);
            //如果是空指，大量的缓存击穿
            return pictureVOPage;
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
        return null;
    }

    private Page<PictureVO> getPageByCache(String cacheKey){
        // 从caffeine中查询，如果命中，caffeine和redis中都进行一个简单的续期，弄成一个简单的冷热分离
        String caffeineCache = LOCAL_CACHE.getIfPresent(cacheKey);
        if (caffeineCache != null) {
            //如果查到了，给redis进行一个续期
            valueOps.getAndExpire(cacheKey,randomExpireTime(),TimeUnit.SECONDS);

            Page<PictureVO> cachedPage = JSONUtil.toBean(caffeineCache, Page.class);
            return cachedPage;
        }
        // 从 Redis 缓存中查询
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        String cachedValue = valueOps.get(cacheKey);

        valueOps.getAndExpire(cacheKey,randomExpireTime(),TimeUnit.SECONDS);
        if (cachedValue != null) {
            // 如果缓存命中，返回结果
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            // 存入Caffeine本地缓存
            LOCAL_CACHE.put(cacheKey, cachedValue);
            return cachedPage;
        }
        return null;
    }

    private Page<PictureVO> putPageByCache(Page<PictureVO> pictureVOPage,String cacheKey){
        // 存入 Redis 缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 5 - 10 分钟随机过期，防止雪崩
        int cacheExpireTime = randomExpireTime();
        valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);

        // 存入Caffeine本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        return null;
    }
    private int randomExpireTime(){
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        return cacheExpireTime;
    }

    @Override
    public Boolean updatePictureVOByPageWithCache(PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        //先更新数据库，再更新缓存，如果要保证强一致性
        //那就可以加分布式锁，或者说读写锁
        //再双写的时候，不允许读，在读的时候，不允许写
        //只有在读读的时候，才允许不阻塞
        //这里可以根据业务场景，进行可选
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(LOCK_CACHE_DOUBLE_WRITE);
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            updatePictureVOByPage(pictureUpdateRequest,request);
            //可以直接删除缓存，或者是同步更新缓存
            //可是删除缓存，根据什么删除？根据key，但是，存的时候，存的是
            //queryRequest,这里要修改为图片id的部分作为key，然后id的另一部分和字段值（空间id，地址）
            //
            //但是当用户根据颜色进行缓存时候
        } catch (Exception exception) {

        } finally {
            rLock.unlock();
        }
        return true;
    }
    public Boolean updatePictureVOByPage(PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(StateCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = this.getById(id);
        User loginUser = userService.getLoginUser(request);
        ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR);

        //填充审核参数，更新也要审核
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
        return true;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtil.throwIf(picture == null, StateCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtil.throwIf(ObjUtil.isNull(id), StateCode.PARAMS_ERROR, "id 不能为空");
        // 如果传递了 url，才校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtil.throwIf(url.length() > 1024, StateCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtil.throwIf(introduction.length() > 800, StateCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        String host = cosManager.getHost();
        String path = pictureUrl.replace(host + "/", "");

        // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
//        cosManager.deleteObject(oldPicture.getUrl());
        cosManager.deleteObject(path);
        // 清理缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == 0) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(StateCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(StateCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtil.throwIf(pictureId <= 0, StateCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser == null, StateCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtil.throwIf(!update, StateCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtil.throwIf(oldPicture == null, StateCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();


        // 1. 校验参数
        ThrowUtil.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), StateCode.PARAMS_ERROR);
        ThrowUtil.throwIf(loginUser == null, StateCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtil.throwIf(space == null, StateCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(StateCode.NO_AUTH_ERROR, "没有空间访问权限");
        }

        // 3. 查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);

        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        // 5. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtil.throwIf(!result, StateCode.OPERATION_ERROR);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(StateCode.OPERATION_ERROR, "名称解析错误");
        }
    }


    /**
     * 批量编辑图片分类和标签
     */

//    @Transactional(rollbackFor = Exception.class)
//    public void batchEditPictureMetadata(PictureEditByBatchRequest request, Long spaceId, Long loginUserId) {
//        // 参数校验
////        validateBatchEditRequest(request, spaceId, loginUserId);
//
//        // 查询空间下的图片
//        List<Picture> pictureList = this.lambdaQuery()
//                .eq(Picture::getSpaceId, spaceId)
////                .in(Picture::getId, request.getPictureIds())
//                .list();
//
//        if (pictureList.isEmpty()) {
//            throw new BusinessException(StateCode.NOT_FOUND_ERROR, "指定的图片不存在或不属于该空间");
//        }
//
//        // 分批处理避免长事务
//        int batchSize = 100;
//        List<CompletableFuture<Void>> futures = new ArrayList<>();
//        for (int i = 0; i < pictureList.size(); i += batchSize) {
//            List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));
//
//            // 异步处理每批数据
//            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                batch.forEach(picture -> {
//                    // 编辑分类和标签
//                    if (request.getCategory() != null) {
//                        picture.setCategory(request.getCategory());
//                    }
//                    if (request.getTags() != null) {
//                        picture.setTags(String.join(",", request.getTags()));
//                    }
//                });
//                boolean result = this.updateBatchById(batch);
//                if (!result) {
//                    throw new BusinessException(StateCode.OPERATION_ERROR, "批量更新图片失败");
//                }
//            }, customExecutor);
//
//            futures.add(future);
//        }
//
//        // 等待所有任务完成
//        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//    }
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(StateCode.NOT_FOUND_ERROR));
        // 权限校验
//        checkPictureAuth(loginUser, picture);Sa-Token框架进行权限校验
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

}




